package com.zjitc.service.impl;

import com.zjitc.controller.UserController;
import com.zjitc.mapper.UserMapper;
import com.zjitc.pojo.User;
import com.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    public User getUser(String username) {
        return userMapper.findUserByName(username);
    }

    /**
     * 登录验证方法的实现
     */
    public boolean isLogin(User user) {
        User dbUser = userMapper.findUserByName(user.getUsername());
        return dbUser != null && dbUser.getPassword().equals(user.getPassword()) && dbUser.getRole().equals(user.getRole());
    }

    public List<User> getUsers(int role) {
        switch (role) {
            case 0:
                return userMapper.findUserByRole(0);
            case 1:
                List<User> guard = userMapper.findUserByRole(1);
                guard.addAll(userMapper.findUserByRole(0));
                return guard;
            default:
                return userMapper.findAll();
        }

    }

    @Override
    public void insert(User user) {
        userMapper.insert(user);
    }

    @Override
    public boolean delete(int index) {
        return userMapper.delete(index);
    }

    @Override
    public boolean update(User user) {
        if (userMapper.findUserByName(user.getUsername()) == null || (Objects.equals(user.getId(), userMapper.findUserByName(user.getUsername()).getId()))) {
            return userMapper.update(user);
        }
        return false;
    }

    @Override
    public User findOne(int id) {
        return userMapper.findUserById(id);
    }

    @Override
    public User findByUserName(String username) {
        return userMapper.findUserByName(username);
    }

    @Override
    public List<UserController.BAH> findAllBAH(int id) {
        return userMapper.findAllBAH(id);
    }
}
